import time

import requests
import json
import datetime
import sys
import os
import ntplib
import pandas.io.clipboard as cl
###########################
cl.copy("你好")
actId = 2411070494745331
actGoodIds = [{
    "actGoodId": 585803926,
    "buyQuantity": 1
},{
    "actGoodId": 585803927,
    "buyQuantity": 1
},{
    "actGoodId": 585803930,
    "buyQuantity": 1
},{
    "actGoodId": 585803977,
    "buyQuantity": 1
}]

pay = True # 需要支付
proxies = {"http": None, "https": None}
yanshi = 1.80

user_dict = {
    "userAddrId": 8489403,
    "phone": "15855974178",
    "contactName": "任慧",
    "phoneCode": "86",
    "countryCode": 156,
    "province": "江苏省",
    "city": "南京市",
    "county": "江宁区",
    "positionDetail": "谷里街道锦华路南京碧桂园阅岭苑34栋801",
    "nation": "中国",
    "lon": 0E-12,
    "lat": 0E-12,
    "addressName": "",
    "address": "",
    "defaultStatus": 0
}

headers = {
    "Host": "apipro.qunjielong.com",
    "Connection": "keep-alive",
    "device-type": "10",
    "mini-route": "pro/pages/homepage/customer-homepage/customer-homepage",
    "Authorization": "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjE4MzE2MjM3MCwiZXhwIjoxNzMxNDk4NjEzfQ.9CnKeE95ySr3-gvhqronRyP0Q_c5tFM8ZbxWXisemv5HRwi1Y3LFRkwyxafZtPShmBuKfgkdmc3e28vx7rRWCA",
    "uid": "183162370",
    "companyId": "190",
    "feature-tag": "f0000",
    "qjl-request-level": "LV1",
    "client-version": "5.7.31",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c11)XWEB/11275",
    "Content-Type": "application/json",
    "xweb_xhr": "1",
    "appid": "wx059cd327295ab444",
    "sceneCode": "1256",
    "version": "3.0.0",
    "Accept": "*/*",
    "Sec-Fetch-Site": "cross-site",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://servicewechat.com/wx059cd327295ab444/1939/page-frame.html",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9"
}


###########################
userInfo = {
    "linkMan": user_dict["contactName"],
    "linkPhone": user_dict["phone"],
    "phonePrefix": "86",
    "province": user_dict["province"],
    "city": user_dict["city"],
    "country": user_dict["county"],
    "linkAddress": user_dict["positionDetail"],
    "userAddrId": user_dict["userAddrId"]
}

Authorization = headers.get("Authorization")
logname = os.path.basename(__file__).split('.')[0] + ".log"
if len(sys.argv) > 1:
    yanshi = float(sys.argv[1].strip())
servertime_s = 0
servertime_ms = 0
ntpclient = ntplib.NTPClient()
stime = time.time()
resp = ntpclient.request("ntp.aliyun.com")
etime = time.time()
print(etime, resp.tx_time)
dtime = resp.tx_time - etime + (etime - stime) / 2
if abs(dtime) >= 1:
    servertime_s = dtime // 1
servertime_ms = (dtime % 1) * 1000 // 1

data = {
	"activityId": "{}".format(actId),
	"enterStatus": 1
}
# info_url = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/apply"
# info_url = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/group_buy"
info_url = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/help_sale_child"
proxies = {"http": None, "https": None}
stime = time.time()
res = requests.post(info_url, headers=headers, data=json.dumps(data), proxies=proxies)
dtime_qunjielong = (time.time() - stime) / 2
js = res.json()
stime = datetime.datetime.now()
if js.get("data") and js.get("data").get("activity") and js.get("data").get("activity").get("startTime"):
    stime = datetime.datetime.fromtimestamp(js.get("data").get("activity").get("startTime") / 1000)
    stime -= datetime.timedelta(seconds=1)

print("时差{}.{}".format(int(servertime_s), int(servertime_ms)))
print(stime.strftime("%Y-%m-%d %H:%M:%S"))
print("延时：" + str(yanshi))
print("IO时间:{}ms".format(int(dtime_qunjielong * 1000)))

while (datetime.datetime.now() + datetime.timedelta(seconds=servertime_s) + datetime.timedelta(milliseconds=servertime_ms)) < stime:
    pass

time.sleep(yanshi)

data = {
  "actId": actId,
}


place_all = "https://apipro.qunjielong.com/order-place/api/mina/order_place/place-all"

def run(f_w):
    try:
        data = {
            "groupBuyOrderDTO": {
                "userInfo": userInfo,
                "proOrderItemParamList": actGoodIds,
                "dlvAddrId": 0,
                "proOrderDefExts": [],
                "markInfoJson": {},
                "openGroups": False
            },
            "helpSaleDTO": {
                "userInfo": userInfo,
                "proOrderItemParamList": actGoodIds,
                "dlvAddrId": 0,
                "proOrderDefExts": [],
                "markInfoJson": {},
                "openGroups": False,
                "logisticsModel": 1
            },
            "actId": actId,
            "orderScene": 8012
        }

        res = requests.post(place_all, headers=headers, data=json.dumps(data), proxies=proxies)
        print(res.text)
        f_w.write(json.dumps(res.json(), indent=4, ensure_ascii=False, sort_keys=True))
        f_w.write("\n")
        orderNo = res.json().get("data").get("orderNo")
        query_order_pay_success_toast_list = "https://apipro.qunjielong.com/order-place/api/mina/order_place/query_order_pay_success_toast_list?actId={}&orderNo={}".format(
            actId, orderNo)
        res = requests.get(query_order_pay_success_toast_list, headers=headers, proxies=proxies)
        print(res.text)
        f_w.write(json.dumps(res.json(), indent=4, ensure_ascii=False, sort_keys=True))
        f_w.write("\n")
        if res.json().get("success"):
            if pay:
                payurl = "https://apipro.qunjielong.com/pay-biz/pay/uniPay?actId={}&orderNo={}&useBalancePay=false&useCashier=true".format(actId, orderNo)
                res = requests.post(payurl, data=json.dumps({}), headers=headers,
                                    proxies=proxies)
                f_w.write("########################")
                data = res.json()
                f_w.write(json.dumps(data, indent=4, ensure_ascii=False, sort_keys=True))
                wxsign = json.dumps(data.get("data").get("wxSign"), indent=4, ensure_ascii=False, sort_keys=True)
                cl.copy(wxsign)
                print(wxsign)
                f_w.write("########################")
                f_w.write("\n")

            query_order_personal_home_page = "https://apipro.qunjielong.com/order-cert/api/mina/user-order/query_order_personal_home_page?page=1&pageSize=1"
            res = requests.post(query_order_personal_home_page, data=json.dumps({}), headers=headers, proxies=proxies)
            f_w.write(json.dumps(res.json(), indent=4, ensure_ascii=False, sort_keys=True))
            f_w.write("\n")
            return True
    except Exception as e:
        print(e)
        return False


with open(logname, "w", encoding="utf-8") as f_w:
    for i in range(2):
        f_w.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + "\n")
        if run(f_w):
            break
        time.sleep(0.2)

